<template>
	<div class="link-account">
		<u-navbar title="切换账号">
			<view class="navbar-slot flex">
				<span class="confirm" @click="isModal=true">确定</span>
			</view>
		</u-navbar>
		<u-cell-group>
			<u-cell-item icon="account-fill" :class="accountVal==item.id && 'check'" :title="item.name" v-for="item in accounts" :key="item.id" :arrow="false" @click="accountVal=item.id">
				<u-icon v-if="accountVal==item.id" slot="right-icon" size="32" name="checkmark"></u-icon>
			</u-cell-item>
		</u-cell-group>
		
		<u-modal ref="uModal" v-model="isModal" @confirm="confirm" :show-cancel-button="true" content="是否确定切换账号？" :async-close="true"></u-modal>
		<u-toast ref="uToast" />
	</div>
</template>

<script>
import { linkAccount, observeAccount } from "@/api/user.js";
export default {
	data() {
		return {
			accounts: [],
			accountVal: "",
			isModal: false
		};
	},
	created() {
		let data = uni.getStorageSync("accounts");
		if(!!data.list){
			this.accounts = data.list;
		};
		this.getAccounts();
	},
	methods: {
		getAccounts() {
			linkAccount().then(({data})=>{
				if(data.list){
					uni.setStorageSync("accounts", data);
					this.accounts = data.list;
					this.accountVal = data.current?.id || data.list[0].id;
				}
			});
		},
		confirm() {
			observeAccount({user_id: this.accountVal}).then(({code})=>{
				this.$refs.uModal.clearLoading();
				if(code == 200){
					this.$store.commit("isRefreshAllListHandle", new Date().getTime());
					this.$store.commit("isRefreshImgListHandle", new Date().getTime());
					this.$store.commit("isRefreshVideoListHandle", new Date().getTime());
					this.$store.commit("isRefreshSubjectsListHandle", new Date().getTime());
					this.$refs.uToast.show({
						title: "切换账号成功",
						type: "success",
						callback: ()=>{
							uni.reLaunch({
								url: "/pages/index/index", 
							});
						}
					});
				}
			});
		}
	}
}
</script>

<style lang="scss">
.check{
	color: #1E62FC;
}
.navbar-slot{
	width: 100%;
	justify-content: flex-end;
	padding-right: 30rpx;
	box-sizing: border-box;
	.confirm{
		padding: 10rpx;
		color: #1E62FC;
		font-size: 34rpx
	}
}
</style>
